package com.deyuanyun.pic.settings.aop;

import com.deyuanyun.pic.settings.service.msgtemplate.ParamName;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.MethodParameter;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 消息推送base切面
 *
 * @author axiao(xj08.dream@gmail.com)
 * @version 1.0
 *          Histroy: [修改人][时间][描述]
 * @date 2016-10-09
 */
public class BasePushMsgAspect {

    /**
     * 按照参数名动态的把值放入到EvaluationContext上下文，以便使用SpEL取值
     *
     * @param joinPoint
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-10-09
     */
    final protected EvaluationContext getEvaluationContext(JoinPoint joinPoint) {
        EvaluationContext context = new StandardEvaluationContext();
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        if (args.length > 0) {
            Method method = signature.getMethod();
            for (int i = 0; i < args.length; i++) {
                MethodParameter methodParameter = new MethodParameter(method, i);
                Annotation[] annotations = methodParameter.getParameterAnnotations();
                for (Annotation annotation : annotations) {
                    if(annotation instanceof ParamName) {
                        ParamName paramName = (ParamName) annotation;
                        context.setVariable(paramName.value(), args[i]);
                    }
                }
            }
        }
        return context;
    }
}
